package com.yt.sys.service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import com.yt.sys.mapper.SysRoleMapper;
import com.yt.sys.mapper.SysRolePermissionMapper;
import com.yt.sys.mapper.SysPermissionMapper;
import com.yt.sys.models.dto.SysRoleDTO;
import com.yt.sys.models.dto.SysPermissionDTO;
import com.yt.sys.models.dto.SysRolePermissionDTO;
import com.yt.sys.models.bo.SysRoleSaveBO;
import com.yt.sys.models.service.ISysRoleService;
import com.yt.sys.common.config.YmlConfig;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@DubboService
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRoleDTO> implements ISysRoleService {

    @Autowired
    private YmlConfig ymlConfig;

    @Autowired
    private SysRolePermissionMapper sysRolePermissionMapper;

    @Autowired
    private SysPermissionMapper sysPermissionMapper;

    @Override
    public boolean add(SysRoleSaveBO saveBO) {
        SysRoleDTO dto = new SysRoleDTO();
        BeanUtils.copyProperties(saveBO, dto);
        dto.setId(ymlConfig.getPkId());
        return this.insert(dto);
    }

    @Override
    public List<SysPermissionDTO> getRolePermissions(Long roleId) {
        // 查询角色权限关联
        EntityWrapper<SysRolePermissionDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("role_id", roleId);
        List<SysRolePermissionDTO> rolePermissions = sysRolePermissionMapper.selectList(wrapper);

        // 提取权限ID
        List<Long> permissionIds = rolePermissions.stream()
                .map(SysRolePermissionDTO::getPermissionId)
                .collect(Collectors.toList());

        // 查询权限信息
        if (permissionIds.isEmpty()) {
            return Collections.emptyList();
        }
        return sysPermissionMapper.selectBatchIds(permissionIds);
    }

    @Override
    public boolean assignPermissions(Long roleId, List<Long> permissionIds) {
        // 先删除原有关联
        EntityWrapper<SysRolePermissionDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("role_id", roleId);
        sysRolePermissionMapper.delete(wrapper);

        // 添加新关联
        if (permissionIds != null && !permissionIds.isEmpty()) {
            for (Long permissionId : permissionIds) {
                SysRolePermissionDTO rolePermission = new SysRolePermissionDTO();
                rolePermission.setId(ymlConfig.getPkId());
                rolePermission.setRoleId(roleId);
                rolePermission.setPermissionId(permissionId);
                sysRolePermissionMapper.insert(rolePermission);
            }
        }
        return true;
    }
}